package hung.android.pro1;


import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.TabHost.TabSpec;
import android.widget.ViewSwitcher;

public class hung_pro1Activity extends Activity implements OnClickListener, OnTabChangeListener, TextWatcher {
    /** Called when the activity is first created. */
//--------------Variable Declaration------------------//
	private int  currentScreen =-1;
	
	///tab_1,tab_2,tab_3,tab_4 o day la so thu tu cua cac layout trong ViewFlipper
	public static final int startscreen=0;
    public static final int mainscreen=1;
    public static final int lockscreen=2;
    
    public static final int mtabhost_t1=0;
    public static final int mtabhost_t2=1;
    public static final int mtabhost_t3=2;
	EditText password,username;
	Button login_btn,next_btn,tab1_2_back_btn,import_data,import_save,import_back;
	TextView title,pass,user,currentmoney, currentdatetime;
	ViewFlipper tab1_flippy,tab2_flippy,tab3_flippy;
	Typeface vhtime_font,vntime_font,times_font;
	TabHost th;
	ViewSwitcher master;
	int invalid_counter=0;
	ImageView search;
	EditText money,add_money,sub_money,date_,time_,day_,position,search_edt;
	ListView lv;
	
	AccountDBAdapter entry=new AccountDBAdapter(hung_pro1Activity.this);
	String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());// get date time.
	DateFormat datetime;
	//--------------------------create a ArrayList<object>--------------
	List<HistoryListRow> model;
	HistoryListRow r;
	customlistview_adapter listviewadapter=null;
	//customlistview_adapter newlistadapter=new customlistview_adapter();//
//------------------------------------------------------------------------------------------------------------//
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.master_viewflipper);// The master_viewflipper must contain all widget link of the Application
       //-------------Variable Inititation-----------------//
        title=(TextView)findViewById(R.id.title_txt);
        password=(EditText)findViewById(R.id.edtx_pass);
        username=(EditText)findViewById(R.id.edtx_username);
        pass=(TextView)findViewById(R.id.txt_pass);
        user=(TextView)findViewById(R.id.txt_username);
        currentmoney=(TextView)findViewById(R.id.history_currentmoneytxt);
        tab1_flippy=(ViewFlipper)findViewById(R.id.tab1_viewFlipper1);
        tab2_flippy=(ViewFlipper)findViewById(R.id.tab2_viewFlipper);
        tab3_flippy=(ViewFlipper)findViewById(R.id.tab3_viewFlipper);
        master=(ViewSwitcher)findViewById(R.id.viewSwitcher1)    ; 
        search=(ImageView)findViewById(R.id.search_image);
        search.setOnClickListener(this);
        search_edt=(EditText)findViewById(R.id.edt_search);
        //------------To set event when text is editing--
        search_edt.addTextChangedListener(this);
        //-----------------------------------------------
        next_btn=(Button)findViewById(R.id.next_button);
        login_btn=(Button)findViewById(R.id.btn_login);
        title=(TextView)findViewById(R.id.title_txt);
        
        String time=datetime.getTimeInstance().format(new Date());// get time
        currentdatetime=(TextView)findViewById(R.id.useraccount_textView1);
        currentdatetime.setText(time);
        
        login_btn.setOnClickListener(this);
        next_btn.setOnClickListener(this); //Can't perform if setContentView(R.layout.main), because the main.xml doesn't have Next_btn
        tab1_2_back_btn=(Button)findViewById(R.id.tab1_2_back);
        tab1_2_back_btn.setOnClickListener(this);
        import_data=(Button)findViewById(R.id.Import_databtn);
        import_data.setOnClickListener(this);
        import_save=(Button)findViewById(R.id.import_savebtn);
        import_save.setOnClickListener(this);
        import_back=(Button)findViewById(R.id.import_backbtn);
        import_back.setOnClickListener(this);
        money=(EditText)findViewById(R.id.edt_importmoney);
        add_money=(EditText)findViewById(R.id.edt_import_AddM);
        sub_money=(EditText)findViewById(R.id.edt_import_SubM);
        date_=(EditText)findViewById(R.id.edt_import_date);
        time_=(EditText)findViewById(R.id.edt_import_time);
        day_=(EditText)findViewById(R.id.edt_import_day);
        position=(EditText)findViewById(R.id.edt_import_position);

        
        
        //--------Font setting.---------------------------------------------//
        vhtime_font=Typeface.createFromAsset(getAssets(),"fonts/Vhtime.ttf");
        vntime_font=Typeface.createFromAsset(getAssets(),"fonts/Vntime.ttf");
        times_font=Typeface.createFromAsset(getAssets(),"fonts/times.ttf");
        //----
        title.setTypeface(vhtime_font);
        login_btn.setTypeface(vhtime_font);
        pass.setTypeface(times_font);
        user.setTypeface(times_font);
        //---------------------------------Tabhost Setting----------------------------------------//
        // ------------> Can not declare Tab Host in onCreate().
        // ------------> Because, the created tabhost is not set in the layout displayed in SetContentView.
        //-->(tabhost is not set in main.xml. so, we can't declare tabhost here.
        //*Note: To initiate variable, the XML layout in SetContenView(View) must contain all views declared.
        th=(TabHost)findViewById(R.id.tabhost);
        th.setup();
        TabSpec specs=th.newTabSpec("tag1");
        specs.setContent(R.id.tab1);
        specs.setIndicator("Private",getResources().getDrawable(R.drawable.ic_launcher));
        th.addTab(specs);
        
        specs=th.newTabSpec("tag2");
        specs.setContent(R.id.tab2);
        specs.setIndicator("History",getResources().getDrawable(R.drawable.search_256));
        th.addTab(specs);
        
        specs=th.newTabSpec("tag3");
        specs.setContent(R.id.tab3);
        specs.setIndicator("Routine",getResources().getDrawable(R.drawable.edit_256));
        th.addTab(specs);
      //----------Set event when tab_History is clicked.-------
		//th.getTabWidget().getChildAt(2).setOnClickListener(this);
	    th.setOnTabChangedListener(this);
        //-------------------------------------------------------
        //------------------------------------------------------------------------//
        //	ArrayList<String> chapters= new ArrayList<String>();
	   // customlistview_adapter newlistadapter=new customlistview_adapter();//
	   // listviewadapter=new customlistview_adapter();
        
	    model=new ArrayList<HistoryListRow>();
	    lv=(ListView)findViewById(R.id.history_listView);
        entry.open();
		model=entry.get_arrayData();
        entry.close();
    	lv.setAdapter(new ArrayAdapter<HistoryListRow>(this,R.layout.listview_row,model));
		
    	//lv.setAdapter(newlistadapter);
		
	
    }
//-------------OnClickListener-------------//
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		//-----------------Login Processing-----------------------------------//
		case R.id.btn_login:{
			String pass,user;
			pass=(String)password.getText().toString();
			user=(String)username.getText().toString();
			if((pass.contentEquals("hungoanh"))&&(user.contentEquals("hungcop")))
			{  Toast.makeText(getBaseContext(), "Correct!You are Welcome!", 3000).show();
				master.showNext();
			}// end of if
			else {    
				invalid_counter+=1;
				if(invalid_counter==3)setContentView(R.layout.lock_screen);
				new AlertDialog.Builder(this)
				.setTitle("Invalid!")
				.setMessage("You have entered invalid account imformation! Try again!")
				.setIcon(R.drawable.icon_dialog_warning)
				.setNeutralButton("Close", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					}
				}).show();
				
				
			};//end of else */
		//master.showNext();
			}//end of case
		break;
		//------------------------------------------------------------------------------//
				
		case R.id.next_button:showscreen(tab1_flippy,1,true);break;                
		case R.id.tab1_2_back:showscreen(tab1_flippy,0,true);break;
		case R.id.search_image:Toast.makeText(getBaseContext(), "Hey girl!", 3000).show();break;
		case R.id.Import_databtn:showscreen(tab2_flippy,1,true);break;
		case R.id.import_savebtn:
			boolean didItWork=true;
			try{
			String imoney=money.getText().toString();
			String iadd_money=add_money.getText().toString();
			String isub_money=sub_money.getText().toString();
			String idate=date_.getText().toString();
			String itime=DateFormat.getTimeInstance().format(new Date());
			String iday=day_.getText().toString();
			String iposition=position.getText().toString();
			
			
			AccountDBAdapter entry=new AccountDBAdapter(hung_pro1Activity.this);
			entry.open();
			entry.add_row(imoney,iadd_money,isub_money,idate,itime,iday,iposition);
			entry.close();
			
			}catch (Exception e){
				didItWork=false;
				String error=e.toString();
				Dialog d=new Dialog(this);
				d.setTitle("Fault!")	;
				TextView tv=new TextView(this);
				tv.setText(error);
				d.setContentView(tv);
				d.show();
			}finally{
				if(didItWork){
				Dialog d=new Dialog(this);
				d.setTitle("Oh,YEAH!")	;
				TextView tv=new TextView(this);
				tv.setText("Success");
				d.setContentView(tv);
				d.show();
				money.setText("");
				add_money.setText("");
				sub_money.setText("");
				date_.setText("");
				time_.setText("");
				day_.setText("");
				position.setText("");
				
				}
				
			}
			break;
			
		case R.id.import_backbtn:showscreen(tab2_flippy,0,true);break;
		
		
		}// end of switch
		//---
		// case R.id.btn_login:{};break;
		
		
	}//end of void onClick()
	
//--------------------Called when a tabWidget of TabHost is clicked-------------------------//
	@Override
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		if(tabId.equals("tag2")){
			customlistview_adapter newlistadapter=new customlistview_adapter();//
			entry.open();
			model=entry.get_arrayData();
	        entry.close();
	     	lv.setAdapter(newlistadapter);
			
			
		}
		}	
//--------------------Called when editText is editted--------------------------	

	@Override
	public void beforeTextChanged(CharSequence s, int start,
			int count, int after) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onTextChanged(CharSequence s, int start,
			int before, int count) {
		// TODO Auto-generated method stub
		Toast.makeText(getBaseContext(), "EditText is being editing!",1000).show();
		
	}
	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}
//---------------------------------------------------
	    @Override
		protected void onStart() {
			// TODO Auto-generated method stub
			super.onStart();
		}

		@Override
		protected void onRestart() {
			// TODO Auto-generated method stub
			super.onRestart();
		}

		@Override
		protected void onResume() {			// TODO Auto-generated method stub
			super.onResume();
		}

		@Override
		protected void onPause() {
			// TODO Auto-generated method stub
			super.onPause();
		}

		@Override
		protected void onStop() {
			// TODO Auto-generated method stub
			super.onStop();
		}

		@Override
		protected void onDestroy() {
			// TODO Auto-generated method stub
			super.onDestroy();
		}	
	
	
//********************************My class, method() Definition***********************************//
//---------------------------Custom ListView Adapter----------------------------------------------//
public class customlistview_adapter extends ArrayAdapter<HistoryListRow>{
//--------------Constructor-----------///
        customlistview_adapter() {super(hung_pro1Activity.this, R.layout.listview_row, model);	  }
//------------------------
		public View getView(int position, View convertView, ViewGroup parent) {
			View row=convertView;
			Listview_rowHolder holder=null;
				 if (row==null) {                         
				        LayoutInflater inflater=getLayoutInflater();
				        row=inflater.inflate(R.layout.listview_row, parent, false);
				        holder=new Listview_rowHolder(row);
				        row.setTag(holder);
				      }
				      else {
				        holder=(Listview_rowHolder)row.getTag();
				      }
				      
				      holder.populateFrom(model.get(position));
				      
				      return(row);
				    }
				  }
//----------------			  
static class Listview_rowHolder {
				    private TextView date=null;
				    private TextView position=null;
				    private ImageView icon=null;
				    //----------------------------------------------------//
				    Listview_rowHolder(View row) {
				     date=(TextView)row.findViewById(R.id.row_textView1);
				     position=(TextView)row.findViewById(R.id.row_textView2);
				     icon=(ImageView)row.findViewById(R.id.row_imageView1);
				    }
				    //-----------------------------------------//
				    void populateFrom(HistoryListRow r) {
				      date.setText(r.gettime()+" "+r.getDate());
				      position.setText(r.getPosition()+" "+r.getAddMoney() +" "+r.getSubMoney() + " "+r.getMoney());
				      
				      if (r.getSubMoney().equals("0")) {icon.setImageResource(R.drawable.add_icon);}
				      else if (r.getAddMoney().equals("0")) {icon.setImageResource(R.drawable.sub_icon);}
				      else icon.setImageResource(R.drawable.ic_launcher);
				 				                       				    }
				               }	
//----------------------------Searching-----------------------------------------------------------//
		public void searching(){
			String i;
			//i.trim().codePointCount(beginIndex, endIndex);
		}
		
//--------------------View Flipper Animation------------------------------------------------------//	
	 private void showscreen(ViewFlipper flippy,int newSlide, boolean n2c) {
			if (n2c && newSlide == currentScreen) return; 
			flippy.setInAnimation(inFromDownRightAnimation());
		    flippy.setOutAnimation(outToUpLeftAnimation());
					
	     //   flippy.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left))	;	
	   //     flippy.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
	         flippy.setDisplayedChild(newSlide); 
	 }
    //-------------------------Fade_In_Animation----------------------------------------------------//
	 private Animation fade_in_Animation()
	 {Animation in;
	 in=AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
	 in.setDuration(1000);
    	return in;
		 
	 }
	 
	 
	//-------------------------Fade_Out_Animation---------------------------------------------------//
	 private Animation fade_out_Animation()
	 {Animation out;
	 out=AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
	 out.setDuration(1000);
	 	return out;
		 
	 }
	//-------------------------slide_Out_right Animation---------------------------------------------------//
		 private Animation slide_out_right_Animation()
		 {Animation out;
		 out=AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
		 out.setDuration(1000);
		 	return out;
			 
		 }
		//-------------------------slide_Out_right Animation---------------------------------------------------//
		 private Animation slide_in_left_Animation()
		 {Animation in;
		 in=AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
		 in.setDuration(1000);
		 	return in;
			 
		 }
	 
	 
	//-----------------------In from Right, Out from Left-------------------------------------//
	 	   private Animation inFromRightAnimation() {
				Animation inFromRight = new TranslateAnimation(
						Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
						);
				inFromRight.setDuration(500);
				inFromRight.setInterpolator(new AccelerateInterpolator());
				return inFromRight;
			}

			private Animation outToLeftAnimation() {
				Animation outtoLeft = new TranslateAnimation(
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
						);
				outtoLeft.setDuration(500);
				outtoLeft.setInterpolator(new AccelerateInterpolator());
				return outtoLeft;
			} 
	        //----------------In form Left, Out from Right---------------------------------------------//
			private Animation inFromLeftAnimation() {
				Animation inFromRight = new TranslateAnimation(
						Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
						);
				inFromRight.setDuration(500);
				inFromRight.setInterpolator(new AccelerateInterpolator());
				return inFromRight;
			}
			private Animation outToRigthAnimation() {
				Animation outtoLeft = new TranslateAnimation(
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  1.0f,
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
						);
				outtoLeft.setDuration(500);
				outtoLeft.setInterpolator(new AccelerateInterpolator());
				return outtoLeft;
			} 
	    
	       //----------------------------------In from Up, out from down---------------------------//
			private Animation inFromUpAnimation() {
				Animation inFromRight = new TranslateAnimation(
						///X coordinator
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
						// Y coordinator
						Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,   0.0f
						);
				inFromRight.setDuration(500);
				inFromRight.setInterpolator(new AccelerateInterpolator());
				return inFromRight;
			}
			private Animation outToDownAnimation() {
				Animation outtoLeft = new TranslateAnimation(
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
						Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  1.0f
						);
				outtoLeft.setDuration(500);
				outtoLeft.setInterpolator(new AccelerateInterpolator());
				return outtoLeft;
			} 
	    
	          //---In from Down, out from Up--------------------------------------------------------//
				private Animation inFromDownAnimation() {
					Animation inFromRight = new TranslateAnimation(
							///X coordinator
							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
							// Y coordinator
							Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,   0.0f
							);
					inFromRight.setDuration(500);
					inFromRight.setInterpolator(new AccelerateInterpolator());
					return inFromRight;
				}
				private Animation outToUpAnimation() {
					Animation outtoLeft = new TranslateAnimation(
							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   -1.0f
							);
					outtoLeft.setDuration(500);
					outtoLeft.setInterpolator(new AccelerateInterpolator());
					return outtoLeft;
				} 
		    
	            //----In from Down Right; Out from Up Left----------------------------------------------//
				private Animation inFromDownRightAnimation() {
					Animation inFromRight = new TranslateAnimation(
							///X coordinator
							Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
							// Y coordinator
							Animation.RELATIVE_TO_PARENT,  1.0f, Animation.RELATIVE_TO_PARENT,   0.0f
							);
					inFromRight.setDuration(500);
					inFromRight.setInterpolator(new AccelerateInterpolator());
					return inFromRight;
				}
				private Animation outToUpLeftAnimation() {
					Animation outtoLeft = new TranslateAnimation(
							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
							Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   -1.0f
							);
					outtoLeft.setDuration(500);
					outtoLeft.setInterpolator(new AccelerateInterpolator());
					return outtoLeft;
				}
				
				
				
			
				
				
	
}// End of Main Activity